import { and, eq } from "drizzle-orm";
import z from "zod";
import { auth } from "../lib/auth";
import { db } from "../lib/db";
import { member } from "../schemas/auth";

export async function getUserOrgsWithAllMembers(userId: string) {
  const data = await db.query.organization.findMany({
    where: (org, { exists }) =>
      exists(
        db
          .select()
          .from(member)
          .where(and(eq(member.userId, userId), eq(member.organizationId, org.id))),
      ),
    with: {
      members: {
        with: {
          user: true,
        },
      },
    },
  });
  return data;
}

export const AddMemberSchema = z.object({
  organizationId: z.string().min(1),
  userId: z.string().min(1),
  role: z.enum(["admin", "member"]),
});

export async function addMember(data: z.infer<typeof AddMemberSchema>) {
  const response = await auth.api.addMember({
    body: data,
  });
  return response;
}
